package com.zenithmind.exam.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import com.zenithmind.exam.pojo.entity.QuestionFavorite;
import com.zenithmind.exam.pojo.vo.QuestionVO;
import com.zenithmind.exam.service.QuestionFavoriteService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 题目收藏控制器
 * 
 * @author ZenithMind
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/api/exam/question-favorite")
@RequiredArgsConstructor
@Validated
@Tag(name = "题目收藏管理", description = "题目收藏的相关操作")
public class QuestionFavoriteController {

    private final QuestionFavoriteService questionFavoriteService;

    @PostMapping("/{questionId}")
    @Operation(summary = "收藏题目", description = "收藏指定的题目")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> favoriteQuestion(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId) {
        String userId = UserContext.getUserId();
        boolean result = questionFavoriteService.favoriteQuestion(userId, questionId);
        return Result.success(result);
    }

    @DeleteMapping("/{questionId}")
    @Operation(summary = "取消收藏题目", description = "取消收藏指定的题目")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> unfavoriteQuestion(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId) {
        String userId = UserContext.getUserId();
        boolean result = questionFavoriteService.unfavoriteQuestion(userId, questionId);
        return Result.success(result);
    }

    @GetMapping("/{questionId}/is-favorited")
    @Operation(summary = "检查是否收藏", description = "检查用户是否收藏了指定题目")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> isFavorited(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId) {
        String userId = UserContext.getUserId();
        boolean result = questionFavoriteService.isFavorited(userId, questionId);
        return Result.success(result);
    }

    @GetMapping("/my-favorites")
    @Operation(summary = "获取我的收藏", description = "获取当前用户收藏的题目列表")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<QuestionVO>> getMyFavoriteQuestions() {
        String userId = UserContext.getUserId();
        List<QuestionVO> questions = questionFavoriteService.getUserFavoriteQuestions(userId);
        return Result.success(questions);
    }

    @GetMapping("/my-favorites/page")
    @Operation(summary = "分页查询我的收藏", description = "分页查询当前用户收藏的题目")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<IPage<QuestionVO>> getMyFavoriteQuestionPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        
        String userId = UserContext.getUserId();
        Page<QuestionFavorite> page = new Page<>(pageNum, pageSize);
        IPage<QuestionVO> result = questionFavoriteService.getUserFavoriteQuestionPage(page, userId);
        return Result.success(result);
    }

    @GetMapping("/my-favorites/count")
    @Operation(summary = "统计我的收藏数量", description = "统计当前用户收藏的题目数量")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Integer> getMyFavoriteCount() {
        String userId = UserContext.getUserId();
        Integer count = questionFavoriteService.countUserFavorites(userId);
        return Result.success(count);
    }

    @GetMapping("/question/{questionId}/count")
    @Operation(summary = "统计题目收藏次数", description = "统计指定题目被收藏的次数")
    public Result<Integer> getQuestionFavoriteCount(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId) {
        Integer count = questionFavoriteService.countQuestionFavorites(questionId);
        return Result.success(count);
    }

    @GetMapping("/most-favorited")
    @Operation(summary = "获取最受欢迎题目", description = "获取最受欢迎的题目列表")
    public Result<List<QuestionVO>> getMostFavoritedQuestions(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        List<QuestionVO> questions = questionFavoriteService.getMostFavoritedQuestions(limit);
        return Result.success(questions);
    }

    @DeleteMapping("/my-favorites/clear")
    @Operation(summary = "清空我的收藏", description = "清空当前用户的所有收藏")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> clearMyFavorites() {
        String userId = UserContext.getUserId();
        boolean result = questionFavoriteService.clearUserFavorites(userId);
        return Result.success(result);
    }

    @PostMapping("/batch-favorite")
    @Operation(summary = "批量收藏题目", description = "批量收藏指定的题目")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> batchFavoriteQuestions(
            @Parameter(description = "题目ID列表") @RequestBody List<String> questionIds) {
        String userId = UserContext.getUserId();
        boolean result = questionFavoriteService.batchFavoriteQuestions(userId, questionIds);
        return Result.success(result);
    }

    @PostMapping("/batch-unfavorite")
    @Operation(summary = "批量取消收藏题目", description = "批量取消收藏指定的题目")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> batchUnfavoriteQuestions(
            @Parameter(description = "题目ID列表") @RequestBody List<String> questionIds) {
        String userId = UserContext.getUserId();
        boolean result = questionFavoriteService.batchUnfavoriteQuestions(userId, questionIds);
        return Result.success(result);
    }

    @GetMapping("/my-favorites/question-ids")
    @Operation(summary = "获取我的收藏题目ID", description = "获取当前用户收藏的题目ID列表")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<String>> getMyFavoriteQuestionIds() {
        String userId = UserContext.getUserId();
        List<String> questionIds = questionFavoriteService.getUserFavoriteQuestionIds(userId);
        return Result.success(questionIds);
    }
}
